class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix.length == 0 || matrix[0].length == 0)
        {
            return new int[0];
        }
        int row=matrix.length;
        int col=matrix[0].length;
        int d=0;
        int top=0;
        int left=0;
        int bottom=row-1;
        int right=col-1;
        int n=row*col;
        int[] res=new int[n];
        while(left<=right&&top<=bottom){
        for(int i=left;i<=right;i++)
        {
            res[d]=matrix[top][i];
            d++;
        }
        for(int i=top+1;i<=bottom;i++)
        {
            res[d]=matrix[i][right];
            d++;
        }
        if(left<right&&top<bottom){
        for(int i=right-1;i>left;i--)
        {
            res[d]=matrix[bottom][i];
            d++;
        }
        for(int i=bottom;i>top;i--)
        {
            res[d]=matrix[i][left];
            d++;
        }
        }
        left++;
        right--;
        top++;
        bottom--;
        }
        return res;
    }
}
